package com.cupk.carManageMaster.core.serviceImpl;
/**
 * @Software: IntelliJ IDEA
 * @Project: car-manage-master
 * @File: PersonalServiceImpl.java
 * @Author: 箬玉
 * @Description: 人事接口实现
 * @Date: 2023/6/4 15:27
 */

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.cupk.carManageMaster.common.domain.ResponseBase;
import com.cupk.carManageMaster.common.dto.DriverDto;
import com.cupk.carManageMaster.common.dto.PersonalDto;
import com.cupk.carManageMaster.common.enums.ErrorEnum;
import com.cupk.carManageMaster.common.mapper.PersonalMapper;
import com.cupk.carManageMaster.core.service.PersonalService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.*;


/**
 * @ClassName: PersonalServiceImpl
 * @Author: 箬玉
 * @Description: 人事Service层实现类
 * @Date: 2023/6/4 15:27
 */
@Service
@Transactional
@Slf4j
public class PersonalServiceImpl extends BaseApiServiceImpl implements PersonalService {
    private final PersonalMapper personalMapper;

    public PersonalServiceImpl(PersonalMapper personalMapper) {
        this.personalMapper = personalMapper;
    }


    /**
     * 批量导入司机信息
     *
     * @param excelData
     * @return 成功200, 返回成功数 失败400，返回错误
     */
    @Override
    public ResponseBase uploadDriver(String excelData) {
        JSONObject jsonData = JSONObject.parseObject(excelData);
        JSONArray jsonDataArray = jsonData.getJSONArray("excelData");
        int count = 0;
        List<String> idNumberList = new ArrayList<>();
//        Map<String, String> errorMsg = new HashMap<>();
        for (int i = 0; i < jsonDataArray.size(); i++) {
            String idNumber = jsonDataArray.getJSONObject(i).getString("id_number");
            if (personalMapper.isExistIdNumber(idNumber) != 0) {
                idNumberList.add(idNumber);
                continue;
            }
            Long typeCarId = getCarType(jsonDataArray.getJSONObject(i).getString("type_car"));
            if (typeCarId == 1000L || typeCarId == 100L) {
                idNumberList.add(idNumber);
                continue;
            }
            Integer drivingExperience = Integer.parseInt(jsonDataArray.getJSONObject(i).getString("driving_experience"));
            String employeeName = jsonDataArray.getJSONObject(i).getString("employee_name");
            Integer age = Integer.parseInt(jsonDataArray.getJSONObject(i).getString("age"));
            String phoneNumber = jsonDataArray.getJSONObject(i).getString("phone_number");
            Integer privilegeLevel = getPrivilegeTypeId("司机");
            String jobNumber = getNewJobNumber(privilegeLevel);
            String photoUrl = "101.200.182.134:8080/picture/2.jpg";
            count++;
            try {
                personalMapper.insertJobUser(jobNumber, employeeName, age, privilegeLevel, idNumber, photoUrl, phoneNumber);
                Long userId = personalMapper.getJobUserId(jobNumber);
                personalMapper.insertDriverUser(userId, drivingExperience, typeCarId);
            } catch (Exception e) {
                idNumberList.add(idNumber);
                count--;
//                errorMsg.put("errorMsg", e.toString());
//                return setResultError(e.toString());
            }
        }
        return setResult(200, Integer.toString(count), idNumberList);
//        if (errorMsg.isEmpty()) {
//            return setResult(200, Integer.toString(count), errorMsg);
//        } else {
//            return setResultSuccess(Integer.toString(count));
//        }
    }

    /**
     * 批量导入其他人员信息
     *
     * @param excelData
     * @return 成功200, 返回成功数 失败400，返回错误
     */
    @Override
    public ResponseBase uploadOther(String excelData) {
        JSONObject jsonData = JSONObject.parseObject(excelData);
        JSONArray jsonDataArray = jsonData.getJSONArray("excelData");
        int count = 0;
        List<String> idNumberList = new ArrayList<>();
//        Map<String, String> errorMsg = new HashMap<>();
        for (int i = 0; i < jsonDataArray.size(); i++) {
            String idNumber = jsonDataArray.getJSONObject(i).getString("id_number");
            if (personalMapper.isExistIdNumber(idNumber) != 0) {
                idNumberList.add(idNumber);
                continue;
            }
            String employeeName = jsonDataArray.getJSONObject(i).getString("employee_name");
            Integer age = Integer.parseInt(jsonDataArray.getJSONObject(i).getString("age"));
            String phoneNumber = jsonDataArray.getJSONObject(i).getString("phone_number");
            Integer privilegeLevel = getPrivilegeTypeId(jsonDataArray.getJSONObject(i).getString("privilege"));
            String jobNumber = getNewJobNumber(privilegeLevel);
            String photoUrl = "101.200.182.134:8080/picture/2.jpg";
            count++;
            try {
                personalMapper.insertJobUser(jobNumber, employeeName, age, privilegeLevel, idNumber, photoUrl, phoneNumber);
            } catch (Exception e) {
                count--;
                idNumberList.add(idNumber);
//                errorMsg.put("errorMsg", e.toString());
//                return setResultError(e.toString());
            }
        }
        return setResult(200, Integer.toString(count), idNumberList);
//        if (errorMsg.isEmpty()) {
//            return setResult(200, Integer.toString(count), errorMsg);
//        } else {
//            return setResultSuccess(Integer.toString(count));
//        }
    }

    /**
     * 查询司机人员列表
     *
     * @return 司机人员列表
     */
    @Override
    public ResponseBase getDriver() {
        List<DriverDto> driverList;
        try {
            driverList = personalMapper.getDriverList(0);
        } catch (Exception e) {
            return setResultError(e.toString());
        }
        if (driverList.size() == 0) {
            log.error(ErrorEnum.SQL_EMPTY_ERROR.getMessage());
            return setResultError(ErrorEnum.SQL_EMPTY_ERROR.getMessage());
        } else {
            return setResultSuccess(driverList);
        }
    }

    /**
     * 查询其他人员列表
     *
     * @param privilegeLevel
     * @return 其他人员列表
     */
    @Override
    public ResponseBase getOther(Integer privilegeLevel) {
        List<PersonalDto> otherList;
        try {
            otherList = personalMapper.getOtherList(privilegeLevel);
        } catch (Exception e) {
            return setResultError(e.toString());
        }
        if (otherList.size() == 0) {
            log.error(ErrorEnum.SQL_EMPTY_ERROR.getMessage());
            return setResultError(ErrorEnum.SQL_EMPTY_ERROR.getMessage());
        } else {
            return setResultSuccess(otherList);
        }
    }

    /**
     * 司机信息修改
     *
     * @param objectData
     * @return
     */
    @Override
    public ResponseBase changeDriver(String objectData) {
        JSONObject jsonData = JSONObject.parseObject(objectData);
        String typeCar = jsonData.getString("type_car");
        Long typeCarId = getCarType(typeCar);
        if (typeCarId == 1000L || typeCarId == 100L) {
            log.error(ErrorEnum.CAR_TYPE_ERROR.getMessage());
            return setResultError(ErrorEnum.CAR_TYPE_ERROR.getMessage());
        }
        Long id = jsonData.getLong("id");
        String employeeName = jsonData.getString("employee_name");
        Date entryTime = new Date(jsonData.getLong("entry_time"));
        Integer age = jsonData.getInteger("age");
        Integer drivingExperience = jsonData.getInteger("driving_experience");
        String idNumber = jsonData.getString("id_number");
        String phoneNumber = jsonData.getString("phone_number");
        try {
            personalMapper.changeUser(id, employeeName, entryTime, age, idNumber, phoneNumber);
            personalMapper.changeDriver(id, drivingExperience, typeCarId);
        } catch (Exception e) {
            return setResultError(e.toString());
        }
        return setResultSuccess();
    }

    /**
     * 其他人员信息修改
     *
     * @param objectData
     * @return
     */
    @Override
    public ResponseBase changeOther(String objectData) {
        JSONObject jsonData = JSONObject.parseObject(objectData);
        Long id = jsonData.getLong("id");
        String employeeName = jsonData.getString("employee_name");
        Date entryTime = new Date(jsonData.getLong("entry_time"));
        Integer age = jsonData.getInteger("age");
        String idNumber = jsonData.getString("id_number");
        String phoneNumber = jsonData.getString("phone_number");
        try {
            personalMapper.changeUser(id, employeeName, entryTime, age, idNumber, phoneNumber);
        } catch (Exception e) {
            return setResultError(e.toString());
        }
        return setResultSuccess();
    }

    /**
     * 司机信息删除
     *
     * @param id
     * @return
     */
    @Override
    public ResponseBase deleteDriver(Long id) {
        try {
            personalMapper.deleteDriver(id);
            personalMapper.deleteUser(id);
        } catch (Exception e) {
            return setResultError(e.toString());
        }
        return setResultSuccess();
    }

    /**
     * 其他人员信息删除
     *
     * @param id
     * @return
     */
    @Override
    public ResponseBase deleteOther(Long id) {
        try {
            personalMapper.deleteUser(id);
        } catch (Exception e) {
            return setResultError(e.toString());
        }
        return setResultSuccess();
    }

    /**
     * 通用员工信息查询
     *
     * @param jobNumber
     * @return
     */
    @Override
    public ResponseBase searchCurrent(String jobNumber) {
        int privilegeLevel = Integer.parseInt(jobNumber.substring(4, 6));
        if (privilegeLevel == 0) {
            try {
                return setResult(200, "司机", personalMapper.getDriver(jobNumber));
            } catch (Exception e) {
                return setResultError(e.toString());
            }
        } else {
            try {
                return setResult(200, getPrivilegeType(privilegeLevel), personalMapper.getOther(jobNumber));
            } catch (Exception e) {
                return setResultError(e.toString());
            }
        }
    }

    /**
     * 密码修改
     *
     * @param oldPassword
     * @param newPassword
     * @param id
     * @return
     */
    @Override
    public ResponseBase changePassword(String oldPassword, String newPassword, Long id) {
        if (personalMapper.verifyPassword(id, oldPassword) != 1) {
            log.error(ErrorEnum.MYSQL_SERVER_ERROR.getMessage());
            return setResultError(ErrorEnum.MYSQL_SERVER_ERROR.getMessage());
        } else {
            try {
                personalMapper.changePassword(id, newPassword);
            } catch (Exception e) {
                return setResultError(e.toString());
            }
            return setResultSuccess();
        }
    }

    /**
     * 根据车型文字查询所代表的数字
     *
     * @param typeCar
     * @return 汽车车型代表的数字
     */
    private Long getCarType(String typeCar) {
        Long carTypeId;
        try {
            carTypeId = personalMapper.getCarTypeId(typeCar);
        } catch (Exception e) {
//            System.out.println(e.toString());
            carTypeId = 1000L;
        }
        if (carTypeId == null) {
            carTypeId = 100L;
        }
        return carTypeId;
    }

    /**
     * 根据权限级别文字查询所代表的数字
     *
     * @param type
     * @return 权限级别代表的数字
     */
    private Integer getPrivilegeTypeId(String type) {
        return switch (type) {
            case "司机" -> 0;
            case "人事" -> 1;
            case "行政" -> 2;
            case "卡口工作人员" -> 3;
            case "信息部人员" -> 4;
            default -> 100;
        };
    }

    /**
     * 根据权限级别文字查询所代表的数字
     *
     * @param typeId
     * @return 权限级别代表的数字
     */
    private String getPrivilegeType(Integer typeId) {
        return switch (typeId) {
            case 0 -> "司机";
            case 1 -> "人事";
            case 2 -> "行政";
            case 3 -> "卡口工作人员";
            case 4 -> "信息部人员";
            default -> "类型错误";
        };
    }

    /**
     * 根据权限生成工号
     *
     * @param typeId
     * @return 新生成的工号
     */
    private String getNewJobNumber(Integer typeId) {
        LocalDate localDate = LocalDate.now();
        String year = Integer.toString(localDate.getYear());
        String jobNumberHead = year + "0" + typeId;
        String search = jobNumberHead + "____";
        List<String> jobListString = personalMapper.getDriverJobNumberList(search);
        List<Integer> jobListInt = new ArrayList<Integer>();
        for (String s : jobListString) {
            jobListInt.add(Integer.parseInt(s.substring(6)));
        }
        if (jobListInt.size() == 0) {
            jobListInt.add(0);
        }
        StringBuilder maxIdString = new StringBuilder(Integer.toString(Collections.max(jobListInt) + 1));
        while (maxIdString.length() < 4) {
            maxIdString.insert(0, "0");
        }
        maxIdString.insert(0, jobNumberHead);
        return maxIdString.toString();
    }

}
